/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tom.social.fetcher.agent.behaviour;

import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import java.util.Date;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import pl.tom.social.common.jade.TaskBarProxy;
import pl.tom.social.dal.SocialDatabaseFacade;
import pl.tom.social.dal.entity.Site;
import pl.tom.social.fetcher.crawler.CrawlerFacade;

/**
 *
 * @author Tom
 */
public class FetchNodeBehaviour extends OneShotBehaviour {

	private static final Logger logger = Logger.getLogger(FetchNodeBehaviour.class);
	private Thread download;

	public FetchNodeBehaviour(final String url, final AID receiver, Thread download) {
		Runnable r = new Runnable() {

			public void run() {
				TaskBarProxy taskBar = new TaskBarProxy(myAgent, receiver);
				fetch(url, taskBar);
				taskBar.finish();
				myAgent.doDelete();
			}
		};
		download = new Thread(r);
		this.download = download;
	}

	@Override
	public void action() {
		if(!download.isAlive()) {
			download.start();
		}
	}

	private void fetch(String url, TaskBarProxy taskBar) {
		try {
			SocialDatabaseFacade db = new SocialDatabaseFacade();

			Site site = db.getSite(url);
			if(site == null) {
				site = new Site(url);
				db.persistEntity(site);
			}

			CrawlerFacade.processNode(site, taskBar);

			site.setUpdated(new Date());
			db.mergeEntity(site);
		} catch(Exception ex) {
			logger.log(Level.ERROR, null, ex);
		}
	}
}

